import { auth } from '@/libs'
import { getConfig } from '@/settings'
/**
 * 访问控制插件
 */
export default {
    /**
     *
     * @param {*} Vue vue
     * @param {Object} options 访问控制选项
     */
    install(Vue, options) {
        const DEFAULT_WHITE_LIST = [
            getConfig().auth.LOGIN_ROUTE_NAME,
            ...getConfig().auth.WHITE_LIST,
        ]
        const {
            loginRoute = getConfig().auth.LOGIN_ROUTE_NAME,
            whiteList = [],
            onTokenExpired,
        } = options
        const _whiteList = whiteList.length ? whiteList : DEFAULT_WHITE_LIST
        console.debug('[vue-access-control] installed')
        console.debug(
            '[vue-access-control] DEFAULT_WHITE_LIST',
            DEFAULT_WHITE_LIST
        )
        const { router } = options
        router.beforeEach(async (to, from, next) => {
            console.debug('[router beforeEach]', to.fullPath, from.fullPath)
            console.debug(
                '[router beforeEach auth.validate()]',
                auth.validate()
            )
            console.debug(
                '[router beforeEach _whiteList.includes(to.name)]',
                _whiteList.includes(to.name)
            )
            if (auth.validate() > 0 || _whiteList.includes(to.name)) {
                next()
            } else {
                if (onTokenExpired instanceof Function) {
                    // 令牌过期回调
                    await onTokenExpired()
                }
                next({ name: loginRoute })
            }
        })
    },
}
